package cn.kgc.easybuy.service.impl;

import cn.kgc.easybuy.dao.CategoryMapper;
import cn.kgc.easybuy.exception.MyRuntimeException;
import cn.kgc.easybuy.pojo.Category;
import cn.kgc.easybuy.service.CategoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @program: yingzi-wants-to-sleep
 * @description:
 * @author: 敖成
 * @create: 2025-09-11 14:47
 **/
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> selectAllCategory() {
        return categoryMapper.selectAllCategory();
    }

    @Override
    public PageInfo<Category> selectCategoryByPage(Map<String, Object> params) {
        PageHelper.startPage(params);
        List<Category> categoryList = categoryMapper.selectCategoryByPage(params);
        return new PageInfo<>(categoryList);
    }

    @Override
    public List<Category> selectChildCategory(Integer parentId) {
        return categoryMapper.selectChildCategory(parentId);
    }

    @Override
    public List<Category> selectCategoryByType(Integer type) {
        return categoryMapper.selectCategoryByType(type);
    }

    @Override
    public List<Category> selectChildren(Integer parentId) {
        return categoryMapper.selectChildren(parentId);
    }

    @Override
    public List<Category> selectRootCategories() {
        return categoryMapper.selectRootCategories();
    }

    @Override
    public boolean delCategory(Integer id) {
        Category category = categoryMapper.selectCategoryById(id);
        if (category.getType() == 3) {
            categoryMapper.delCategory(id);
            return true;
        }
        if (categoryMapper.selectChildCategory(id).size() != 0){
            throw new MyRuntimeException("该分类下还有子分类，无法删除！");
        }
        return categoryMapper.delCategory(id) > 0;
    }

    @Override
    public boolean addCategory(Category category) {
        return categoryMapper.addCategory(category) > 0;
    }

    @Override
    public boolean updateCategory(Category category) {
        return categoryMapper.updateCategory(category) > 0;
    }

    @Override
    public Category selectCategoryById(Integer id) {
        return categoryMapper.selectCategoryById(id);
    }

    @Override
    public boolean checkName(String name,Integer type) {
        return categoryMapper.checkName(name,type) > 0 ? false : true;
    }
}
